package al.il.technion.cs236635.project.tests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.jgroups.ChannelException;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.util.Util;

public class Test {

	private JChannel channel;
	
	public Test( ) {
		try {
			channel = new JChannel( );
			channel.connect( "simple");
			channel.setReceiver( new ReceiverAdapter( ) {
				@Override
				public void receive(Message msg) {
					try {
						String message = new String(  msg.getBuffer( ));
						if ( msg.getSrc( ) != channel.getAddress()) {
							System.out.println( channel.getName( ) + " said > " + message);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
			});
			String line = "";
			BufferedReader reader = new BufferedReader( new InputStreamReader( System.in));
			try {
				while ( !line.equals( "EXIT")) {
					try {
						line = reader.readLine( );
						try {
							channel.send( null, null, line.getBytes( ));
						} catch (Exception e) {
							e.printStackTrace();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} finally {
				try {
					reader.close( );
				} catch (IOException e) {
				}
			}
		} catch (ChannelException e) {
			e.printStackTrace();
		} finally {
			channel.close( );
		}
	}
	
	public static void main(String[] args) {
		Test test = new Test( );
	}
}
